package com.chen.jwt.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.jwt.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 若晨
 * @version 1.0.0
 * @ClassName JWTInterceptor.java
 * @Description TODO
 * @createTime 2022年08月02日 22:06:00
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();

        //获取请求头中令牌
        String token = request.getHeader("token");
        try {
            JWTUtils.getTokenInfo(token);//验证令牌
            return true;//放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace( ) ;
            map.put ( "msg" , "签名不⼀致" ) ;
        } catch (TokenExpiredException e) {
            e.printStackTrace( ) ;
            map.put ( "msg" , "令牌过期" ) ;
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace( ) ;
            map.put ( "msg" , "算法不匹配" ) ;
        } catch (InvalidClaimException e) {
            e.printStackTrace( ) ;
            map.put( "msg" , "失效的payload" ) ;
        } catch (Exception e) {
            e.printStackTrace( ) ;
            map . put ( "msg" , "token⽆效" ) ;
        }
        map.put("state",false);//设置状态
        //将map转为json jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
